<?php
session_start(); //we need to call PHP's session object to access it through CI
class Login_Controller extends Controller {

	public function __construct() {
		parent::Controller();

		$this->load->helper(array('form','url'));
		$this->load->library('form_validation');
	}

	public function index() {
		$this->load->view('login_form');
	}

	public function submit() {

		if ($this->_submit_validate() === FALSE) {
			$this->index();
			return;
		}
		
		redirect('/home');
		

	}

	private function _submit_validate() {

		$this->form_validation->set_rules('tendangnhap', 'Tên đăng nhập',
			'trim|required|callback_authenticate');

		$this->form_validation->set_rules('matkhau', 'Mật khẩu',
			'trim|required');

		$this->form_validation->set_message('authenticate','Đăng nhập thất bại. Vui lòng kiểm tra lại.');

		return $this->form_validation->run();
	
	}

	public function authenticate() {
//
//		// get User object by username
//		if ($u = Doctrine::getTable('User')->findOneByTaikhoan($this->input->post('tendangnhap'))) {
//
//			// this mutates (encrypts) the input password
//			$u_input = new User();
//			$u_input->matkhau = $this->input->post('matkhau');
//
//			// password match (comparing encrypted passwords)
//			if ($u->matkhau == $u_input->matkhau) {
//				unset($u_input);
//				$CI =& get_instance();
//				$this->session->set_userdata('logged_in', $u_input);
//				return TRUE;
//			}
//			unset($u_input);
//		}
		return Current_User::login($this->input->post('tendangnhap'), $this->input->post('matkhau'));
	}
}
